package com.drool.mediaplayer;



import com.drool.mediaplayer.Adapters.AlbumBrowserAdapter;
import com.drool.mediaplayer.Adapters.VideoBrowserAdapter;
import com.drool.mediaplayer.Database.MediaFilesDB;
import com.drool.mediaplayer.Database.MediaFilesDBHelper;
import com.drool.mediaplayer.Database.WritableDatabase;
import com.drool.mediaplayer.Extracter.AudioInfoExtracter;
import com.drool.mediaplayer.Extracter.VideoInfoExtracter;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import java.util.Calendar;
import java.text.SimpleDateFormat;


public class MediaLibraryBrowser extends Activity {

	private Bundle extras;
	private static final String TAG = "Drool:MediaLibraryBr";
	//private AudioInfoExtracter aExtracter = new AudioInfoExtracter();
	//private VideoInfoExtracter vExtracter = new VideoInfoExtracter();
	
	private MediaFilesDBHelper myDBHelper;
	private SQLiteDatabase db;
	private WritableDatabase wDB = new WritableDatabase(MediaLibraryBrowser.this);
	private ViewFlipper flipper;
	private int customContext;
	private static final int audioAlbumContext = 1;
	private static final int videoAlbumContext = 2;
	private static final int songContext = 3;
	private Cursor c;
	Playlist pl;
	
	
	@Override
	public void onCreate(Bundle icicle) {
		String [] columnList= new String[9];
		String sortColumn = new String();
		super.onCreate(icicle);
		setContentView(R.layout.laymedialibbr);
		
		myDBHelper = new MediaFilesDBHelper(this);
		db = myDBHelper.getReadableDatabase();
		
		
		
		flipper=(ViewFlipper)findViewById(R.id.details);
		
		flipper.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
		flipper.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
		
		Button btnRt=(Button)findViewById(R.id.Button01);

		btnRt.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				flipper.showNext();
			}
		});
		btnRt.setVisibility(View.INVISIBLE);
		
		Button btnLt=(Button)findViewById(R.id.Button02);

		btnLt.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				flipper.showPrevious();
			}
		});
		
		btnLt.setVisibility(View.INVISIBLE);
		
		Button labelViewButton = (Button)findViewById(R.id.Button03);
		labelViewButton.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MediaLibraryBrowser.this.getApplicationContext(), 
						LabelViewBrowser.class);
				startActivity(intent);
			}
		});
			
		extras = getIntent().getExtras();
		TextView txtv = (TextView) findViewById(R.id.LibHeader);
		if (extras.getInt(MediaLibrary.TYPE) == MediaLibrary.MUSIC){
			txtv.setText("All Albums");
			
			//TODO Code for Music library updates		
			//Select the table for MUSIC files
			//call a function to populate the library UI
			customContext = audioAlbumContext;
			columnList[0] = Audio.Albums._ID;
			columnList[1] = Audio.Albums.ALBUM;
			columnList[2] = Audio.Albums.ALBUM_ART;
			columnList[3] = Audio.Albums.ARTIST;
			columnList[4] = Audio.Albums.FIRST_YEAR;
			columnList[5] = Audio.Albums.NUMBER_OF_SONGS;
			
			sortColumn = Audio.Albums.ALBUM;
			
			//setAlbumView(null,null,null,columnList,sortColumn);
			showAudioAlbums(columnList, sortColumn);
			//check to see if new audio exists
			
		} 
		else{
			txtv.setText("All Videos");
			//TODO Code for Video library updates
			//Select the table for Video files
			//call a function to populate the library UI
			
			customContext = videoAlbumContext;
			
			columnList[0]= Video.Media._ID;
			columnList[1]=Video.Media.TITLE;
			columnList[2]=Video.Media.ALBUM;
			columnList[3]=Video.Media.ARTIST;
			columnList[4]=Video.Media.DATE_ADDED;
			columnList[5]=Video.Media.DISPLAY_NAME;			
			columnList[6]=Video.Media.DURATION;
			columnList[7]=Video.Media.DESCRIPTION;
			
			sortColumn = Video.Media.DATE_ADDED;
			
			//setAlbumView(qTables,qWhereClause,qGroupBy,columnList,sortColumn);
			showVideoInfo(columnList,new String [] {
							MediaStore.Video.Media.DISPLAY_NAME,
							MediaStore.Video.Media.ARTIST},sortColumn);
			
				
		}
		
		SharedPreferences settings = getSharedPreferences(MyPreferences.PREFERENCE_NAME,0);
		
		pl = null;
		Log.i(TAG, "settings Playlist " + settings.getLong(MyPreferences.ACTIVE_PLAYLIST, -1));
		if (settings.getLong(MyPreferences.ACTIVE_PLAYLIST, -1) == -1){
			pl = new Playlist(Playlist.PLAYLIST_TYPE_NEW, MediaLibraryBrowser.this, "Now Playing");
			Log.i(TAG, "Creating new playlist");
		}else{
			pl = new Playlist(settings.getLong(MyPreferences.ACTIVE_PLAYLIST, -1), MediaLibraryBrowser.this);
		}
		
		Log.i(TAG, "Active Playlist " + Long.toString(pl.getActivePlaylist()));
		if (pl.getActivePlaylist() == -1){
			Log.i(TAG, "No active playlist could be attached");
		}
		else{
			SharedPreferences.Editor prefEditor = settings.edit();
			prefEditor.putLong(MyPreferences.ACTIVE_PLAYLIST, pl.getActivePlaylist());					
			prefEditor.commit();
		}
		switch (settings.getInt(MyPreferences.SHUFFLE_STATE, -1)){
			case MyPreferences.SHUFFLE_STATE_VALUE_OFF:
				pl.setShuffle(Playlist.PLAYLIST_SHUFFLE_OFF);
				break;
			case MyPreferences.SHUFFLE_STATE_VALUE_ON:
				pl.setShuffle(Playlist.PLAYLIST_SHUFFLE_ON);
				break;	
			default:
				pl.setShuffle(Playlist.PLAYLIST_SHUFFLE_OFF);
				break;
		}
	
		switch (settings.getInt(MyPreferences.LOOP_STATE, -1)){
			case MyPreferences.LOOP_STATE_VALUE_OFF:
				pl.setLoop(Playlist.PLAYLIST_LOOP_OFF);
				break;
			case MyPreferences.LOOP_STATE_VALUE_ON:
				pl.setLoop(Playlist.PLAYLIST_LOOP_ON);
				break;	
			default:
				pl.setLoop(Playlist.PLAYLIST_LOOP_OFF);
				break;
		}
		
	}	
	
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		db.close();
		myDBHelper.close();
	}


	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	

	private void showAudioAlbums(String [] columnList, String sortColumns )
	{
		final ListView lv;	
		
		
		
		Uri album = Audio.Albums.EXTERNAL_CONTENT_URI;
		//String[] projection3 = new String[] {Audio.Albums._ID,Audio.Albums.ALBUM, Audio.Albums.ALBUM_ART};
		
		final Cursor aCursor = managedQuery(album, columnList, null, null, sortColumns);
		startManagingCursor(aCursor);	
		
		Log.i(TAG, "Total Albums found: " + Integer.toString(aCursor.getCount()));
		
		AlbumBrowserAdapter browserAdapter = new AlbumBrowserAdapter(this, aCursor);
		lv = ((ListView)findViewById(R.id.ListView01));
		lv.setAdapter(browserAdapter);
		
		OnItemClickListener mListListener = new OnItemClickListener() {
			
			@Override
			 public void onItemClick(AdapterView parent, View v, int position, long id)
			 {        // Display a messagebox.        
				 //Toast.makeText(mContext,"You've got an event",Toast.LENGTH_SHORT).show();
					aCursor.moveToPosition(position);
					displayAudioAlbumInfo(aCursor.getString(0), aCursor.getString(2),
							aCursor.getPosition());					
			 }
			
		};
		lv.setOnItemClickListener(mListListener);
		
		lv.setOnItemLongClickListener(new OnItemLongClickListener(){

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int position, long arg3) {
				AlertDialog alertDialog = new AlertDialog.Builder(MediaLibraryBrowser.this).create();
			    alertDialog.setTitle("Add album to playlist");
			    alertDialog.setMessage("Do you want to add this album to the playlist?");
			    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {
			    	  aCursor.moveToPosition(position);
			    	  
			    	  Uri songUri = Audio.Media.EXTERNAL_CONTENT_URI;
			    	  
			    	  final Cursor songCursor = managedQuery(songUri, new String [] {
			    			  Audio.Media._ID
			    	  }, Audio.Media.ALBUM_ID + "= "+ aCursor.getString(0) , null, null);
			  		  startManagingCursor(songCursor);
			  		  if (songCursor.getCount() > 0){
			  			  songCursor.moveToFirst();
			  			  while (!songCursor.isAfterLast()){
			  				try {
								pl.updatePlaylist(songCursor.getString(0));								
							} catch (InvalidPlaylistException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
			  				songCursor.moveToNext();
			  			  }
			  			Toast.makeText(MediaLibraryBrowser.this, "Album added to the playlist",Toast.LENGTH_SHORT).show();
			  		  }
						
			  		  songCursor.close();
			    	  return;
			      } }); 
			    alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
				      public void onClick(DialogInterface dialog, int which) {
				        return;
				      } });
				
			    alertDialog.show();
				return true;
			}
			
		});
		
	}
	
	private void showVideoInfo(String [] columnList, String [] adapterCols, String sortColumns )
	{
		ListView lv;	
		
		Uri video = Video.Media.EXTERNAL_CONTENT_URI;		
		
		final Cursor vCursor = managedQuery(video, columnList, null, null, sortColumns);
		startManagingCursor(vCursor);	
		
		Log.i(TAG, "Total Albums found: " + Integer.toString(vCursor.getCount()));
		
		/*
		ListAdapter adapter = new SimpleCursorAdapter(
				this, R.layout.layadapter,
			    vCursor, adapterCols, new int[] {
			        R.id.text1,
			        R.id.text2
			    });
		*/
		
		VideoBrowserAdapter vAdapter = new VideoBrowserAdapter(this, vCursor);
		lv = ((ListView)findViewById(R.id.ListView01));
		lv.setAdapter(vAdapter);
		OnItemClickListener mListListener = new OnItemClickListener() {
			
			@Override
			 public void onItemClick(AdapterView parent, View v, int position, long id)
			 {        // Display a messagebox.        
				 //Toast.makeText(mContext,"You've got an event",Toast.LENGTH_SHORT).show();
					vCursor.moveToPosition(position);
					showVideo(vCursor.getString(0));
			 }
		};
		lv.setOnItemClickListener(mListListener);
		
	}
	
	private void displayAudioAlbumInfo(String albumId, String albumArt, int cursorPos){		
		
		Intent intent = new Intent(MediaLibraryBrowser.this.getApplicationContext(), 
				SongAlbumBrowser.class);
		
		intent.putExtra(SongAlbumBrowser.SELECTION, SongAlbumBrowser.SELECTION_ONE);
		intent.putExtra(SongAlbumBrowser.DATA, albumId);
		//intent.putExtra(SongAlbumBrowser.DATA1, albumArt);
		intent.putExtra(SongAlbumBrowser.DATA1, cursorPos);
		startActivity(intent);		
	}
	
	/*
	private void displayAudioAlbumInfo(String albumId){
		Cursor cur;
		String [] columnList = new String[2];
		
		columnList[0] = MediaFilesDB.FileHeader.HDR_TABLE_NAME + "." + MediaFilesDB.FileHeader._ID + " as _id";
		columnList[1] = MediaFilesDB.FileHeader.HDR_DISP_NAME;
		
		String qTables = new String (MediaFilesDB.FileHeader.HDR_TABLE_NAME + " ," +MediaFilesDB.AudioFiles.AUDIO_TABLE_NAME);
		String qWhereClause = new String 
					(MediaFilesDB.AudioFiles.AUDIO_TABLE_NAME + "." + MediaFilesDB.AudioFiles.AUDIO_ALBUM_ID 
					 + " = '" + albumId + "'" 
					 + " and " + MediaFilesDB.FileHeader.HDR_FILE_ID + " = " + MediaFilesDB.AudioFiles.AUDIO_TABLE_NAME + "." 
					 + MediaFilesDB.AudioFiles._ID
					 + " and " + MediaFilesDB.FileHeader.HDR_FILE_TYPE + " = \'a\'");
		
		
		//sortColumn = MediaFilesDB.AudioFiles.AUDIO_ALBUM;
		
		SQLiteDatabase db = myDBHelper.getReadableDatabase();		
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
		
		queryBuilder.setTables(qTables);
		queryBuilder.appendWhere(qWhereClause);
		
		cur = queryBuilder.query(db,columnList , null, null,null,null,null);
		startManagingCursor(cur);
		
		cur.moveToFirst();
		while (!cur.isAfterLast()){
			Log.i(TAG, cur.getString(1));
			cur.moveToNext();
		}
	}
	*/
	
	private void showVideo(String videoId){
		//attach ID with URI and start playback
		Intent intent = new Intent(MediaLibraryBrowser.this.getApplicationContext(), 
				MediaPlayerActivity.class);
		intent.putExtra(MediaPlayerActivity.TYPE, MediaPlayerActivity.VIDEO);
		intent.putExtra(MediaPlayerActivity.DATA, videoId);
		startActivity(intent);
	}
	
	
}

